package handler

import (
	"encoding/json"
	"file-master/cache"
	"file-master/modler"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var post []modler.Past

	redis_list_key := "list_page_" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		//从mysql读取数据
		modler.DB.Offset(offset).Limit(size).Debug().Find(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &post)
	}

	var total int64

	modler.DB.Model(&modler.Past{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "成功",
		"total": total,
		"data":  post,
	})
	return
}

func Lists(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var post []modler.Past

	redis_list_ley := "list_post" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_ley).Result()
	if result == "" {
		modler.DB.Offset(offset).Limit(size).Find(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_list_ley, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &post)
	}

	var total int64

	modler.DB.Model(&modler.Past{}).Count(&total)

	c.JSON(200, gin.H{
		"mas":   "获取成功",
		"code":  200,
		"total": total,
		"data":  post,
	})
	return

}

func Login(c *gin.Context) {
	id := c.Query("id")
	var post modler.Past

	redis_list_ley := "list_post" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_ley).Result()
	if result == "" {
		modler.DB.Where("id=?", id).First(&post)
		jsonData, _ := json.Marshal(post)
		cache.Rdb.Set(cache.Ctx, redis_list_ley, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &post)
	}

	c.JSON(200, gin.H{
		"mas":  "搜索成功",
		"code": 200,
		"data": post,
	})
	return
}
